package com.wd.live.tool

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson

/**
 *@Author Nick.wu
 *Date 2023/8/14
 */
class LoginHelper {

    companion object {
        const val USER_INFO = "user_info"

        @JvmStatic
        fun saveWXLoginCode(context: Context, code: String) {
            val sp = context.getSharedPreferences("login_info", Context.MODE_PRIVATE)
            sp.edit().putString("wx_code", code).apply()
        }

        fun getWxLoginCode(context: Context): String? {
            val sp = context.getSharedPreferences("login_info", Context.MODE_PRIVATE)
            return sp.getString("wx_code", null)
        }


    }
}


fun Context.saveLoginInfo(data: LocalData.UserInfo?) {
    val json = data?.let {
        Gson().toJson(it)
    }
    val sp = this.getSharedPreferences("login_info", Context.MODE_PRIVATE)
    sp.edit().putString(LoginHelper.USER_INFO, json).apply()
}

fun Context.isLogin(): Boolean {
    val loginInfo = getLoginInfo()
    return loginInfo.userId != null && loginInfo.sessionId != null
}
fun Context.getUserId(): Int? {
    val loginInfo = getLoginInfo()
    return loginInfo.userId
}

fun Context.getSessionId(): String? {
    val loginInfo = getLoginInfo()
    return loginInfo.sessionId
}
fun Context.getLoginInfo(): LocalData.UserInfo {
    val sp = this.getSharedPreferences("login_info", Context.MODE_PRIVATE)
    val json = sp.getString(LoginHelper.USER_INFO, null)
    return json?.let {
        Gson().fromJson(json, LocalData.UserInfo::class.java)
    } ?: LocalData.UserInfo()

}